import { InboxOutlined, PlusOutlined, DownloadOutlined, ToTopOutlined, SmileOutlined, DeleteOutlined ,AndroidOutlined,UndoOutlined} from '@ant-design/icons';
import { ProTable, PageContainer } from '@ant-design/pro-components';
import { Button, Upload, Space, Input, message, Modal, Form, Select, DatePicker, notification, Alert } from 'antd';
import { useRef, useState, useEffect } from 'react';
import { GetInput, PatchInput, PostInput } from "@/api/SampleClothing"
import { useModel } from 'umi';
import moment from 'moment';
import D from '@/components/utils/ExcelViews'
import { UploadExcel, DownloadExcel } from '@/api/SampleClothing';
import { flattenObject } from "@/components/utils/Tools"
import Marquee from 'react-fast-marquee';

const { Dragger } = Upload;
const { Option } = Select;
const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 16 },
};
const tailLayout = {
    wrapperCol: { offset: 8, span: 16 },
};

function InputTable() {
    const actionRef = useRef();
    const [inputTable, setInputTable] = useState()
    const [total, setTotal] = useState(0)
    const [isModalOpen, setIsModalOpen] = useState(false); // 添加数据-弹出层设置
    const [isModalOpen02, setIsModalOpen02] = useState(false); // 导入数据数据-弹出层设置
    const [form] = Form.useForm(); // 添加数据的表单
    const { initialState, setInitialState } = useModel('@@initialState'); // 获取State持久化数据
    const userId = initialState.currentUser.userinfo.id
    const username = initialState.currentUser.userinfo.username
    const [fileData, setFileData] = useState({})  // 
    // const [fileList, setFileList] = useState() // 上传的文件列表
    const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 初始化选中的行 keys  
    const [api, contextHolder] = notification.useNotification(); // 弹出信息框
    const permissions = initialState.currentUser.permissionslist;

    const openNotificationWithIcon = (type: NotificationType) => {
        api[type]({
            message: '上传成功',
            description:
                '文件已经成功上传，赶紧刷新列表查看吧~',
        });
    };
    const openNotificationWithIcon02 = (type: NotificationType) => {
        api[type]({
            message: '上传失败',
            description:
                '抱歉，文件上传失败了~',
        });
    };
    function flattenArray(arr) {
        return arr.map(item => flattenObject(item));
    }
    // 获取数据
    const GetData = async (options) => {
        try {
            const data = await GetInput(options)
            console.log("INputDta", flattenArray(data.results))
            setInputTable(flattenArray(data.results))
            setTotal(data.count)
            // message.success("查询成功")
        } catch (err) {
            message.error("查询失败！")
        }
    }
    // 修改数据 
    const PatchData = async (id, options) => {
        try {
            const { kind_max, plate_name, plate_price, plate_count, color, size, person, plate_date, plate_Comment, localtion } = options
            const data = await PatchInput(id, { kind_max, plate_name, plate_price, plate_count, color, size, person, plate_date, plate_Comment, localtion, update_name: username })
            // console.log(data)
            // 展平保存
            const patchinputTable = inputTable.map(item => {
                if (item.id === id) {
                    return flattenObject(data)
                }
                return item
            })
            setInputTable(patchinputTable)
            message.success("修改成功!")
        } catch (err) {
            message.error("修改失败！")
        }
    }
    // 添加数据
    const AddData = async (options) => {
        try {
            const data = await PostInput({ ...options, 'user_id': userId })
            const postdata = flattenObject(data)
            setInputTable([...inputTable, postdata])
            message.success("成功添加!")
        } catch (err) {
            message.error("添加失败！")
        }
    }
    const handleCancel = () => {
        setIsModalOpen(false);
    };
    // 清空表单信息
    const onReset = () => {
        form.resetFields();
    };
    // 提交表单 
    const onFinish = (values: any) => {
        console.log("表单提交信息：", values);

        // const { activitycount, activitydescribe, activityposstion, activitystatus, activityname } = values
        // const [startDateStr, endDateStr] = values.activitydate
        const plate_Date = moment(values.plate_date).format('YYYY-MM-DD');
        // console.log(plate_Date)
        const { kind_max, plate_name, plate_price, plate_count, color, size, person, plate_Comment, localtion } = values
        AddData({ kind_max, plate_name, plate_price, plate_count, color, size, person, plate_Comment, localtion, 'plate_date': plate_Date })
        message.success('入库成功~');
    };
    // 上传取消
    const UploadCancel = () => {
        setFileData({})
        setIsModalOpen02(false)

    }
    // 导入数据处理函数
    const UploadData = async (file) => {
        const formData = new FormData();
        formData.append('file', file);
        formData.append('D_put', 'input');
        try {
            const response = await UploadExcel(formData);
            if (response.status === 200) {
                // message.success("上传成功！")
                openNotificationWithIcon('success')
                actionRef.current.reload();
                UploadCancel()
                return
            }
            openNotificationWithIcon02('error')
            message.info("文件格式出现异常")
        } catch (error) {
            openNotificationWithIcon02('error')
            // 处理上传失败的逻辑
            message.error("上传失败！")
        }
    }
    // 导出数据
    const DownloadData = async () => {
        try {
            // 不能为空
            if (selectedRowKeys.length === 0) {
                message.info('请选择您要导出的数据')
                return
            }
            const reponse = await DownloadExcel({ 'file': 'input', 'IdList': selectedRowKeys })
            console.log(reponse)
            // const blob = await response.blob();
            const blob = new Blob([reponse], { type: 'application/octet-stream' })

            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            const now = new Date();
            const formattedTime = now.toISOString().slice(0, 10).replace(/-/g, '_') + '_' + now.toTimeString().slice(0, 5).replace(/:/g, '_');
            link.setAttribute('download', `${formattedTime}_入库表.xlsx`);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
            // message.success("下载成功~");
            message.success("导出成功")
        } catch (err) {
            console.log(err)
            message.error("导出失败")
        }
    }
    // 批量删除
    const DeleteData = async()=>{
        try{
            if (selectedRowKeys.length === 0) {
                message.info('请选择您要删除的数据')
                return
            }
            const reponse = await DownloadExcel({ 'file': 'input_delete', 'delete_status':1,'IdList': selectedRowKeys })
            console.log('(reponse',reponse)
            if(reponse){
                actionRef.current.reload();
                message.success('批量删除成功!')
            }

        } catch(err){
            message.error('批量删除失败!')
        }
    }
    // 批量恢复
    const ReSetData = async()=>{
        try{
            if (selectedRowKeys.length === 0) {
                message.info('请选择您要恢复的数据')
                return
            }
            const reponse = await DownloadExcel({ 'file': 'input_delete', 'delete_status':0,'IdList': selectedRowKeys })
            console.log('(reponse',reponse)
            if(reponse){
                actionRef.current.reload();
                message.success('批量恢复成功!')
            }

        } catch(err){
            message.error('批量恢复失败!')
        }
    }
    // 模板下载
    const DownloadModel = async () => {
        try {
            const reponse = await DownloadExcel({ 'file': 'input_model' })
            const blob = new Blob([reponse], { type: 'application/octet-stream' })
            const url = window.URL.createObjectURL(blob);
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', `样衣入库模板表.xlsx`);
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
            message.success("模板下载成功")
        } catch (err) {
            // console.log(err)
            message.error("模板下载失败")
        }
    }
    // 上传确认 
    const UploadOk = () => {
        if (fileData && Object.keys(fileData).length > 0) {
            UploadData(fileData.file.originFileObj)
            // message.success("上传成功")
            return 0
        }
        message.info("暂无数据提供，请上传文件")
        // setIsModalOpen02(false)
    }
    // 用户列表的ID
    const rowSelection = {
        selectedRowKeys,
        onChange: (newSelectedRowKeys, newSelectedRows) => {
            setSelectedRowKeys(newSelectedRowKeys);
            console.log('newSelectedRowKeys', newSelectedRowKeys)
            // 在这里可以处理选中行数据 newSelectedRows
        },
        preserveSelectedRowKeys: true, // 翻页时保留选中状态  
    };
    // 组件初始化 时候运行
    useEffect(() => {
        console.log(permissions.includes('delete_inputtable'))
        
    }, []); // 空数组作为第二个参数，表示只在组件加载时运行一次
    // 表格配置
    const columns = [
        {
            title: '序号',
            dataIndex: 'index',
            valueType: 'index',
            width: 55,
            editable: false,// 编辑禁用
            search: false,
        },
        {
            title: '状态',
            dataIndex: 'is_delete',
            // valueType: 'digit',
            // search: false,
            valueEnum: {
                0: { text: '活跃', status: 'Success' },
                1: { text: '已删除', status: 'Error' },
            },
            hidden: !permissions.includes('delete_inputtable'),
            // render: (text, record) => {
            //     if (record.is_delete) {
            //         return <>未删</>; // 返回 null 或其他值来隐藏列
            //     }
            //     return <>已删</>; // 显示列的内容
            // }

        },
        {
            title: '入库ID',
            dataIndex: 'id',
            width: 66,
            editable: false,// 编辑禁用

            // copyable: true,
            // ellipsis: true,
            // tooltip: '标题过长会自动收缩',
            // formItemProps: {
            //     rules: [
            //         {
            //             required: true,
            //             message: '此项为必填项',
            //         },
            //     ],
            // },
        },
        {
            title: '创建人',
            dataIndex: 'userusername',
            editable: false,// 编辑禁用
            search: false,
            // valueType: '',
        },
        {
            // disable: true,
            title: '大类',
            dataIndex: 'kind_max',

        },
        {
            title: '品名',
            dataIndex: 'plate_name',

        },
        {
            title: '单价',
            dataIndex: 'plate_price',
            valueType: 'money',
            search: false,
        },
        {
            title: '数量',
            dataIndex: 'plate_count',
            valueType: 'digit',
            search: false,

        },
        {
            title: '颜色',
            dataIndex: 'color',
            search: false,
        },
        {
            title: '尺码',
            dataIndex: 'size',
            search: false,
        },
        {
            title: '仓位',
            dataIndex: 'localtion',
        },
        {
            title: '买版人',
            dataIndex: 'person',
        },
        {
            title: '入库时间',
            dataIndex: 'plate_date',
            valueType: 'date',
            ellipsis: true,
            width: 100,
        },
        {
            title: '备注',
            dataIndex: 'person_Comment',
            search: false,
        },
        {
            title: '修改人',
            dataIndex: 'update_name',
            editable: false,// 编辑禁用
            search: false,
        },
        {
            title: '创建时间',
            // key: 'showTime',
            dataIndex: 'created_at',
            valueType: 'dateTime',
            editable: false,// 编辑禁用
            width: 100,
            search: false,
            // width: 48,
            ellipsis: true,
            // copyable: true,
            // sorter: true,
            // hideInSearch: true,
        },
        {
            title: '修改时间',
            dataIndex: 'updated_at',
            valueType: 'dateTime',
            width: 100,
            editable: false,// 编辑禁用
            search: false,
            ellipsis: true,
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            render: (text, record, _, action) => [
                <a
                    key="editable"
                    onClick={() => {
                        action?.startEditable?.(record.id);

                    }}
                >
                    编辑
                </a>,

            ],
        },
    ];
    // 上传文件弹出层
    const props = {
        name: 'file',
        // multiple: true,
        maxCount: 1,
        accept: '.xlsx,.xls',
        onChange(info) {
            const { status } = info.file;
            if (status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (status === 'done') {
                message.success(`${info.file.name} file uploaded successfully.`);
                setFileData(info)
            } else if (status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        },
    };
    return (
        <PageContainer>
            <Alert
                banner
                message={
                    <Marquee pauseOnHover gradient={false}>
                        <span style={{color:'red'}}>误删数据,恢复请联系管理员</span>。<AndroidOutlined spin={true}/> ------ 需要开辟新功能模块或者其他需求，请沟通项目开发人员进行开发~
                    </Marquee>
                }
            />
            <div>
                {contextHolder}
                <Modal width={1300} title="文件上传"
                    open={isModalOpen02}
                    onOk={UploadOk}
                    onCancel={UploadCancel}
                    okText='确认导入数据'
                    cancelText="取消导入"
                >
                    <Dragger {...props}  >
                        <p className="ant-upload-drag-icon">
                            <InboxOutlined />
                        </p>
                        <p className="ant-upload-text">点击上传 或 文件拖拽</p>
                        <p className="ant-upload-hint">
                            （您好，目前仅支持上传后缀.xlsx、.xls的excel文件）
                        </p>
                    </Dragger>
                    <D Props={fileData}></D>
                </Modal>
            </div>
            <ProTable
                bordered
                rowSelection={rowSelection}
                columns={columns}
                actionRef={actionRef}
                cardBordered
                request={async (params, sort, filter) => {
                    console.log("params, sort, filter", params, sort, filter);
                    GetData(params);
                    return {
                        data: inputTable,
                        success: true,
                    }
                }}
                dataSource={inputTable}
                editable={{
                    // type: 'multiple',
                    type: 'single',
                    // editableKeys: editableKeys,
                    onSave: (rowKey, data, row) => {
                        PatchData(rowKey, data);
                    },
                    // 点击删除
                    onDelete: async (rowKey) => {
                        // console.log(rowKey)
                        // PatchData(rowKey,{'is_delete':true})
                        try {
                            await PatchInput(rowKey, { 'is_delete': 1, update_name: username })
                            setInputTable(inputTable.filter((item) => item.id !== rowKey))
                            message.success("删除成功！")
                        } catch (err) {
                            message.error('删除失败！')
                        }
                    },
                    onCancel: () => {
                        message.info('已取消编辑');
                    },
                }}
                columnsState={{
                    persistenceKey: 'pro-table-singe-demos',
                    persistenceType: 'localStorage',
                    defaultValue: {
                        option: { fixed: 'right', disable: true },
                    },
                    onChange(value) {
                        // console.log('value: ', value);
                    },
                }}
                rowKey="id"
                search={{
                    layout: 'vertical',
                    defaultCollapsed: true,
                    labelWidth: 'auto',
                    showHiddenNum: true,
                }}
                options={{
                    setting: {
                        listsHeight: 400,
                    },
                }}
                form={{
                    // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
                    syncToUrl: (values, type) => {
                        if (type === 'get') {
                            return {
                                ...values,
                                created_at: [values.startTime, values.endTime],
                            };
                        }
                        return values;
                    },
                }}
                pagination={{
                    total: total,
                    defaultPageSize: 10,
                    showSizeChanger: true, // 显示可调整每页条数功能
                    pageSizeOptions: ['10', '20', '50', '100'], // 指定每页可以显示多少条
                    showQuickJumper: true, // 显示快速跳转到某页功能
                    // onChange: (page) => console.log(page),
                }}
                dateFormatter="string"
                headerTitle="样衣入库表格"
                toolBarRender={() => [   
                    <Button key="show" icon={< SmileOutlined />} style={{ backgroundColor: '#5dce69', color: "#fff" }} onClick={DownloadModel}>
                        导入模板下载(excel)
                    </Button>,
                    <Button key="show" type="primary" icon={<DeleteOutlined />} danger onClick={DeleteData}>
                        批量删除
                    </Button>,
                    permissions.includes('delete_inputtable') ? (
                        <Button key="show" type="primary" icon={<UndoOutlined />} onClick={ReSetData}>
                          批量恢复删除
                        </Button>
                      ) : null
                    ,
                    <Button key="show" icon={<ToTopOutlined />} onClick={DownloadData} style={{ backgroundColor: '#886ce4', color: "#fff" }}>批量导出</Button>,
                    <Button key="danger" icon={<DownloadOutlined />} danger onClick={() => { setIsModalOpen02(true) }}>
                        批量导入
                    </Button>,
                    <>
                        <Button
                            key="button"
                            icon={<PlusOutlined />}
                            onClick={() => {
                                setIsModalOpen(true);
                            }}
                            type="primary"
                        >
                            新增入库数据
                        </Button>
                        <Modal title="创建样衣入库数据" open={isModalOpen} onCancel={handleCancel} footer={null}>
                            <Form
                                {...layout}
                                form={form}
                                name="control-hooks"
                                onFinish={onFinish}
                                style={{ maxWidth: 600 }}
                            >
                                <Form.Item name="kind_max" label="大类" rules={[{ required: true }]}>
                                    <Select
                                        placeholder="请选择状态~"
                                        allowClear
                                    >
                                        <Option value="61">61</Option>
                                        <Option value="62">62</Option>
                                        <Option value="63">63</Option>
                                        <Option value="64">64</Option>
                                        <Option value="65">65</Option>
                                        <Option value="66">66</Option>
                                        <Option value="67">67</Option>
                                        <Option value="68">68</Option>
                                    </Select>
                                </Form.Item>
                                <Form.Item name="plate_name" label="品名" rules={[{ required: true, message: "此为必填信息" }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item name="plate_price" label="单价" rules={[{ required: true, message: "此为必填信息" }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item label="数量" name="plate_count" rules={[{ required: true, message: 'Please input!' }]}>
                                    <Input />
                                </Form.Item>
                                <Form.Item name="color" label="颜色" >
                                    <Input />
                                </Form.Item>
                                <Form.Item name="size" label="尺码" >
                                    <Input />
                                </Form.Item>
                                <Form.Item name="localtion" label="仓位" >
                                    <Input />
                                </Form.Item>
                                <Form.Item name="person" label="买版人" >
                                    <Input />
                                </Form.Item>
                                <Form.Item name="plate_Comment" label="备注" >
                                    <Input.TextArea />
                                </Form.Item>

                                <Form.Item label="入库时间" name="plate_date" rules={[{ required: true, message: 'Please input!' }]}>
                                    <DatePicker />
                                </Form.Item>
                                <Form.Item {...tailLayout}>
                                    <Space>
                                        <Button type="primary" htmlType="submit">
                                            提交信息
                                        </Button>
                                        <Button htmlType="button" onClick={onReset}>
                                            重置信息
                                        </Button>
                                    </Space>
                                </Form.Item>
                            </Form>
                        </Modal>
                    </>
                    ,

                ]}
            />
        </PageContainer>
    );
};
export default InputTable;
